import { cityList } from '@/api'
import authority from '@/utils/authority'
import { getCurrentOptions } from '@/utils'

export default async () => {
  // 首先取url参数shop_id
  const options = getCurrentOptions()
  if (options.shop_id) return options.shop_id

  // 取缓存shop_id
  const { shop_id } = authority.get() || {}
  if (shop_id) return shop_id
  const { shop = [] } = await cityList() // 获取城市方法中存储了region
  const { regionCode } = authority.get() || {}
  const target = shop.find(item => item.region_code === regionCode)
  if (target) {
    authority.set({
      shop_id: target.shop_id
    })
    return target.shop_id
  } else {
    // 没有返回报错
    return Promise.reject(new Error('not found'))
  }
}
